package com.security.service;

import com.security.auth.ResponseUserToken;
import com.security.auth.UserDetail;
import com.security.check.CustomAuthenticationProvider;
import com.security.config.JwtUtils;
import com.security.entity.CustomWebAuthenticationDetails;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;

/**
 * @description:
 * @author: zyj
 * @create: 2020-01-03 17:17
 **/
@Service
public class AuthService {


    @Autowired
    private AuthenticationManager authenticationManager;


    @Autowired
    private JwtUtils jwtTokenUtil;

    @Value("${jwt.tokenHead}")
    private String tokenHead;

    public ResponseUserToken login(String username, String password, HttpServletRequest httpServletRequest) throws Exception{
        //用户验证
        final Authentication authentication = authenticate(username, password, httpServletRequest);
        //存储认证信息
        SecurityContextHolder.getContext().setAuthentication(authentication);
        //生成token
        final UserDetail userDetail = (UserDetail) authentication.getPrincipal();
        final String token = jwtTokenUtil.generateAccessToken(userDetail);
        //存储token
        jwtTokenUtil.putToken(username, token);
        return new ResponseUserToken(token);

    }

    private Authentication authenticate(String username, String password, HttpServletRequest httpServletRequest) throws Exception{
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(username, password);
        //usernamePasswordAuthenticationToken.setDetails(new CustomWebAuthenticationDetails(httpServletRequest));

        //该方法会去调用userDetailsService.loadUserByUsername()去验证用户名和密码，如果正确，则存储该用户名密码到“security 的 context中”
        return authenticationManager.authenticate(usernamePasswordAuthenticationToken);
    }

}
